<template>
  <div>
    <SearchForm @search="getTableData" @reset="clearSearchForm" :is-search-disabled="isSearchDisabled">
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('用户姓名')">
          <el-input v-model="page.userName"/>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('手机号码')">
          <el-input v-model="page.phone"/>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('营销APP')">
          <el-select style="width: 100%" v-model="page.productName" clearable>
            <el-option v-for="item in marketingProduct" :key="item.productId" :label="item.appName"
                       :value="item.productName"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('营销结果')">
          <el-cascader
              style="width: 100%"
              v-model="page.causeKey"
              :options="selectCause"
              :props="{ checkStrictly: true,value:'key',label:'value' }"
              clearable></el-cascader>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('营销状态')">
          <el-select style="width: 100%" v-model="page.marketingStatus" clearable>
            <el-option :value="1" :label="$t('未注册')"></el-option>
            <el-option :value="2" :label="$t('未申请')"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('IVR按键')">
          <el-select style="width: 100%" v-model="page.ivrResult" clearable>
            <el-option label="0" value="0"></el-option>
            <el-option label="1" value="1"></el-option>
            <el-option label="2" value="2" ></el-option>
            <el-option label="3" value="3"></el-option>
            <el-option label="4" value="4"></el-option>
            <el-option label="5" value="5"></el-option>
            <el-option label="6" value="6"></el-option>
            <el-option label="7" value="7"></el-option>
            <el-option label="8" value="8"></el-option>
            <el-option label="9" value="9"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('IVR结果')">
          <el-select style="width: 100%" v-model="page.result" clearable>
            <el-option :label="$t('成功接通')" value="成功接通"></el-option>
            <el-option :label="$t('未接通')" value="未接通"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('跟进次数')" prop="settlementNum">
          <el-input v-model.number="page.marketingNum" class="input-with-select">
            <el-select style="width: 60px" v-model="page.marketingSymbol"
                       slot="prepend">
              <el-option v-for="item in symbolList" :key="item.label" :label="item.label"
                         :value="item.label"></el-option>
            </el-select>
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item :label="$t('分单时间')">
          <el-date-picker
              v-model="page.distributionTimeValue"
              style="width: 100%"
              unlink-panels
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="~"
              :start-placeholder="$t('开始时间')"
              :end-placeholder="$t('结束时间')">
          </el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item :label="$t('跟进时间')">
          <el-date-picker
              v-model="page.followTimeValue"
              style="width: 100%"
              unlink-panels
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="~"
              :start-placeholder="$t('开始时间')"
              :end-placeholder="$t('结束时间')">
          </el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :span="12" :xs="24">
        <el-form-item :label="$t('申请时间')">
          <el-date-picker
              v-model="page.applyTimeValue"
              style="width: 100%"
              unlink-panels
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="~"
              :start-placeholder="$t('开始时间')"
              :end-placeholder="$t('结束时间')">
          </el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :span="12" :xs="24">
        <el-form-item :label="$t('注册时间')">
          <el-date-picker
              v-model="page.registerTimeValue"
              style="width: 100%"
              unlink-panels
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="~"
              :start-placeholder="$t('开始时间')"
              :end-placeholder="$t('结束时间')">
          </el-date-picker>
        </el-form-item>
      </el-col>
    </SearchForm>
    <el-card shadow="never" style="margin-top: 10px">
      <Table :table-column="tableColumn" :table-data="tableData" :page="page" @handleSizeChange="handleSizeChange"
             :loading="loading"
             @handleCurrentChange="handleCurrentChange">
        <template slot="phone" slot-scope="{row}">
          <el-popover
              placement="right"
              width="120px"
              trigger="click">
            <SelectCallPhone :phone="row.phone" modeType="4" :marketingType="1" :marketingRows="row"/>
            <el-link slot="reference" :underline="false" type="primary">{{
                row.phone
              }}
            </el-link>
          </el-popover>
        </template>
        <template slot="auth" slot-scope="{row}">
          <AuthStatus :row="row"/>
        </template>
        <template slot="result" slot-scope="{row}">
          <div v-if="row.cause1 && row.cause1">
            {{ row.cause1 + '-' + row.cause2 }}
          </div>
        </template>
        <template slot="isBlack" slot-scope="{row}">
          {{ row.isBlack === 0 ? $t('否') : row.isBlack === 1 ? $t('是') : '' }}
        </template>
        <template slot="handle" slot-scope="{row}">
          <el-button type="text" @click="addMarketRecord(row)">{{ $t('备注') }}</el-button>
          <el-button type="text" @click="lookRemark(row)">{{ $t('备注详情') }}</el-button>
        </template>
      </Table>
    </el-card>
    <!--    备注-->
    <Dialog :visible.sync="remarkVisible" :title="$t('备注')" :footer="false" width="60%"
            @close="recordPage.timeValue = null">
      <el-row :gutter="24" style="margin: 0">
        <el-form label-width="80px">
          <el-col :span="12">
            <el-form-item :label="$t('跟进时间')">
              <el-date-picker
                  v-model="recordPage.timeValue"
                  style="width: 100%"
                  unlink-panels
                  value-format="yyyy-MM-dd"
                  type="daterange"
                  range-separator="~"
                  :start-placeholder="$t('开始时间')"
                  :end-placeholder="$t('结束时间')">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12" style="text-align: right">
            <el-button type="primary" @click="marketRemark(tableRows)">{{ $t('查询') }}</el-button>
            <el-button @click="recordPage.timeValue = null,marketRemark(tableRows)">{{ $t('重置') }}</el-button>
          </el-col>
        </el-form>
      </el-row>
      <div>
        <Table style="margin-top: 10px" :table-column="recordColumn" @handleSizeChange="recordSizeChange"
               @handleCurrentChange="recordCurrentChange" :table-data="recordData" :page="recordPage">
          <template slot="result" slot-scope="{row}">
            <div v-if="row.cause1 && row.cause1">
              {{ row.cause1 + '-' + row.cause2 }}
            </div>
          </template>
        </Table>
      </div>
    </Dialog>
    <!--    新增-->
    <Dialog :visible.sync="recordVisible" :title="$t('营销记录')" width="45%" @confirm="recordConfirm"
            @close="recordClearForm"
            @cancel="recordVisible = false">
      <el-form :model="recordForm" ref="recordForm" label-width="80px">
        <el-form-item :label="$t('营销结果')" prop="cause1" :rules="[
          {required: true, message: this.$t('不能为空')},
        ]">
          <el-select v-model="recordForm.cause1" @change="causeChange">
            <el-option v-for="item in marketingCause" v-if="item.code === 0" :key="item.key" :label="item.value"
                       :value="item.key"></el-option>
          </el-select>
          <div style="margin-top: 10px" v-if="marketingTags.length !== 0">
            <el-tag v-for="item in marketingTags" :effect="item.key === recordForm.cause2 ? 'dark' : 'plain'"
                    :key="item.key"
                    @click="tagsClick(item)" :label="item.key" style="margin: 0 10px 10px 0;cursor: pointer">
              {{ item.value }}
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item :label="$t('备注')" prop="remark">
          <el-input type="textarea" v-model="recordForm.remark" :rows="5"></el-input>
        </el-form-item>
      </el-form>
    </Dialog>
  </div>
</template>

<script>
import AuthStatus from '../../registerNotApply/authStatus'
import {selectProduct} from "@/api/system";
import {
  dataBacklogList,
  selectRemarkPage,
  dataAddRemark,
  fetchMarketingCause,
  dataMarketingCallPhone
} from '@/api/marketing'
import {selectChannelName} from '@/api/channel'
import {dateFormatSection} from '@/utils/tools'

export default {
  name: 'registeredAgencyList',
  components: {
    AuthStatus
  },
  data() {
    return {
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        marketingSymbol: '≧'
      },
      marketingProduct: [],
      tableData: [],
      marketPurpose: [
        {label: this.$t('拒绝'), value: 0,},
        {label: this.$t('一般'), value: 1,},
        {label: this.$t('强烈'), value: 2,}
      ],
      symbolList: [
        {label: '>'},
        {label: '='},
        {label: '≧'},
        {label: '≦'},
        {label: '<'}
      ],
      loading: false,
      remarkVisible: false,
      recordVisible: false,
      recordForm: {},
      recordPage: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      recordColumn: [
        {label: this.$t('跟进时间'), prop: 'inputTime', minWidth: 100},
        {label: this.$t('营销结果'), slot: 'result', minWidth: 100},
        {label: this.$t('备注'), prop: 'remark', minWidth: 100},
        {label: this.$t('处理人'), prop: 'userName', minWidth: 100},
      ],
      recordData: [],
      tableRows: {},
      selectCause: [],
      marketingCause: [],
      marketingTags: [],
      isSearchDisabled: false,
      tableColumn: [
        {label: this.$t('用户姓名'), prop: 'userName', minWidth: 100},
        {label: this.$t('手机号码'), slot: 'phone', minWidth: 100},
        {label: this.$t('邮箱'), prop: 'mali', minWidth: 100},
        {label: 'whatsAPP', prop: 'whatsApp', minWidth: 100},
        {label: 'zalo', prop: 'zalo', minWidth: 100},
        // {label: this.$t('身份证号码'), prop: 'idcard', minWidth: 100},
        {label: this.$t('是否黑名单'), slot: 'isBlack', minWidth: 100},
        // {label: this.$t('是否免审核'), prop: 'avoidAudit', minWidth: 100},
        // {label: this.$t('渠道名称'), prop: 'channelName', minWidth: 100},
        {label: this.$t('注册时间'), prop: 'registrationTime', minWidth: 150},
        {label: this.$t('分单时间'), prop: 'allocationTime', minWidth: 150},
        {label: this.$t('营销APP'), prop: 'appName', minWidth: 100},
        {label: this.$t('营销结果'), slot: 'result', minWidth: 100},
        {label: this.$t('IVR按键'), prop: 'ivrResult', minWidth: 100},
        {label: this.$t('IVR结果'), prop: 'result', minWidth: 100},
        {label: this.$t('跟进次数'), prop: 'marketingNum', minWidth: 150},
        {label: this.$t('跟进时间'), prop: 'marketingTime', minWidth: 150},
        {label: this.$t('操作'), slot: 'handle', fixed: 'right', minWidth: 150},
      ],
      callPhoneNumber: null
    }
  },
  mounted() {
    this.getSelect()
    this.getTableData()
  },
  methods: {
    async getTableData() {
      this.isSearchDisabled = true
      const [allocationStart, allocationEnd] = dateFormatSection(this.page.distributionTimeValue || [])
      const [marketingStart, marketingEnd] = dateFormatSection(this.page.followTimeValue || [])
      const [loanStart, loanEnd] = dateFormatSection(this.page.applyTimeValue || [])
      const [registrationTimeStart, registrationTimeEnd] = dateFormatSection(this.page.registerTimeValue)
      const [cause1, cause2] = this.page.causeKey || []
      const params = {
        ...this.page,
        registrationTimeStart, registrationTimeEnd,
        cause1, cause2,
        loanStart, loanEnd,
        allocationStart, allocationEnd, marketingStart, marketingEnd,
        marketingSymbol: this.page.marketingSymbol === '≧' ? '>=' : this.page.marketingSymbol === '≦' ? '<=' : this.page.marketingSymbol,
      }
      delete params.distributionTimeValue
      delete params.followTimeValue
      delete params.applyTimeValue
      delete params.causeKey
      this.loading = true
      const res = await dataBacklogList(params)
      if (res.code === 1) {
        const {list, total} = res.data
        this.tableData = list.map(item => {
          item.result = this.$t(item.result || '')
          item.avoidAudit = item.avoidAudit === 0 ? this.$t('否') : item.avoidAudit === 1 ? this.$t('是') : ''
          return item
        })
        this.page = {
          ...this.page,
          total,
        }
        this.isSearchDisabled = false
        this.loading = false
      } else {
        this.isSearchDisabled = false
        this.loading = false
      }
    },
    lookRemark(row) {
      this.remarkVisible = true
      this.tableRows = {...row}
      this.marketRemark()
    },
    // 获取备注详情
    async marketRemark() {
      const [startTime, endTime] = dateFormatSection(this.recordPage.timeValue || [])
      const params = {
        ...this.page,
        startTime, endTime,
        dataUserId: this.tableRows.dataUserId,
      }
      delete params.timeValue
      const res = await selectRemarkPage(params)
      if (res.code === 1) {
        const {list, pageNum, pageSize, total} = res.data
        this.recordData = list
        this.recordPage = {
          ...this.recordPage,
          pageNum, pageSize, total
        }
      }
    },
    // 打电话
    async callPhone({dataUserId}) {
      const res = await dataMarketingCallPhone({dataUserId: dataUserId})
      if (res.code === 1) {
        this.callPhoneNumber = res.data.phone
      }
    },
    causeChange(key) {
      const list = this.marketingCause.filter(i => i.key === key)
      // 过滤标签列表
      const tageList = list.length ? this.marketingCause.filter(i => i.type === list[0].type && i.code !== 0) : []
      if (tageList.length) this.recordForm.cause2 = tageList[0].key
      this.marketingTags = tageList
    },
    tagsClick({key}) {
      this.recordForm = {
        ...this.recordForm,
        cause2: key
      }
    },
    handleSizeChange(val) {
      this.page.pageSize = val
      this.getTableData()
    },
    handleCurrentChange(val) {
      this.page.pageNum = val
      this.getTableData()
    },
    recordSizeChange(val) {
      this.recordPage.pageSize = val
      this.marketRemark()
    },
    recordCurrentChange(val) {
      this.recordPage.pageSize = val
      this.marketRemark()
    },
    addMarketRecord(row) {
      this.tableRows = {...row}
      this.recordVisible = true
    },
    clearSearchForm() {
      this.page = {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        marketingSymbol: '≧'
      }
      this.getTableData()
    },
    recordClearForm() {
      this.recordForm = {}
      this.marketingTags = []
      this.$refs.recordForm.resetFields()
    },
    recordConfirm() {
      this.$refs.recordForm.validate(async v => {
        if (v) {
          const res = await dataAddRemark({
            ...this.recordForm,
            dataUserId: this.tableRows.dataUserId,
          })
          if (res.code === 1) {
            this.$message.success(this.$t('新增成功'))
            this.getTableData()
            this.marketRemark()
            this.recordVisible = false
          }
        }
      })
    },
    async getSelect() {
      selectProduct().then(res => {
        this.marketingProduct = res.data
      })
      fetchMarketingCause().then(res => {
        this.marketingCause = res.data
        const marketingCause = this.marketingCause.filter(item => {
          if (item.code === 0) {
            const children = this.marketingCause.filter(child => child.type === item.type && child.code !== 0)
            if (children.length > 0) item.children = children
            return item.code === 0
          }
        })
        this.selectCause = marketingCause
      })
    }
  }
}
</script>

<style scoped>

</style>
